<template>
  <el-card shadow="never">
    <div slot="header">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>商品添加</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 提示区域 -->
    <el-alert title="增加商品" type="info" effect="light" show-icon center></el-alert>
    <!-- 主体区域 -->
    <div class="table-box">
      <!-- 步骤条 -->
      <div class="stpes">
        <el-steps :active="activeIndex-0" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内融"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </div>
      <!-- 标签页 -->
      <el-form ref="form" :model="formInfo" :rules="rules" label-width="100px">
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-row>
              <el-col :span="20" :offset="2">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="formInfo.goods_name" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20" :offset="2">
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input v-model="formInfo.goods_price" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20" :offset="2">
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input v-model="formInfo.goods_number" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20" :offset="2">
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input v-model="formInfo.goods_weight" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 级联选择器 -->
            <el-row>
              <el-col :span="20" :offset="2">
                <el-form-item label="商品分类" prop="goods_cat">
                  <el-cascader
                    :options="cat_list"
                    v-model="formInfo.goods_cat"
                    clearable
                    :props="{ label:'cat_name', value:'cat_id' }"
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-row v-for="item in many_list" :key="item.id">
              <el-col :span="20" :offset="2">
                <el-form-item :label="item.attr_name">
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox v-for="(val,idx) in item.attr_vals" :key="idx" :label="val"></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-row v-for="item in only_list" :key="item.id">
              <el-form-item :label="item.attr_name" label-width="150px">
                <el-input v-model="item.attr_vals" clearable></el-input>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img :src="dialogImageUrl" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="formInfo.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button type="primary" size="default" @click="submitGoods">提交</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
  </el-card>
</template>

<script>
// import "quill/dist/quill.core.css";
// import "quill/dist/quill.snow.css";
// import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
// 导入鲁大师
import lodash from "lodash";
// 导入辅助函数
import { mapActions, mapState } from "vuex";
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      activeIndex: "", //激活下标
      // 表单数据
      formInfo: {
        goods_name: "", // 名称
        goods_cat: [351, 356, 363], // 分类id
        goods_price: "", // 价格
        goods_number: "", // 树龄
        goods_weight: "", // 重量
        goods_introduce: "", // 商品介绍
        pics: [], // 图片
        attrs: "", //动态参数和属性
      },
      fileList: [],
      headers: {
        Authorization: JSON.parse(sessionStorage.getItem("userInfo")).token,
      },
      // 验证规则
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      dialogImageUrl: "",
      many_chek_list: [], // 处理后的动态参数
      only_list: [], // 属性
      many_list: [], // 参数
    };
  },
  //   周期函数
  created() {
    console.log(this.cat_list);
    !this.cat_list.length && this.get_cate_all_list();
  },
  //   计算属性
  computed: {
    ...mapState({
      cat_list: (state) => state.cate.cate_all_list,
    }),
    catId() {
      if (this.formInfo.goods_cat.length === 3) {
        return this.formInfo.goods_cat[2];
      } else {
        return null;
      }
    },
  },
  methods: {
    //   获取全部分类
    ...mapActions({
      get_cate_all_list: "cate/get_cate_all_list",
    }),
    // tab栏切换时间
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName == 0 && !this.catId) {
        this.$message.error("请选择分类");
        return false;
      }
    },
    // tab栏切换事件
    async tabClicked() {
      // 准备参数
      let sel = "";
      if (this.activeIndex == "1") {
        sel = "many";
      } else if (this.activeIndex == "2") {
        sel = "only";
      } else {
        return;
      }
      // 发送请求
      let { data: res } = await this.$axios.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel },
        }
      );
      // 错误处理
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      if (sel == "many") {
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
        });
      }
      // 成功保存数据
      this[sel + "_list"] = res.data;
    },
    // 图片预览事件
    handlePreview(file) {
      this.dialogImageUrl = file.response.data.url;
      this.dialogVisible = true;
    },
    // 图片删除事件
    handleRemove(file) {
      let tem_path = file.response.data.tem_path;
      let idx = this.formInfo.pics.findIndex((item) => item.pic == tem_path);
      this.formInfo.pics.splice(idx, 1);
    },
    // 上传成功事件
    handleSuccess(response) {
      this.formInfo.pics.push({
        pic: response.data.tem_path,
      });
    },
    // 表单提交事件
    async submitGoods() {
      // 拷贝一份,防止修改数据是发送异常
      let deepForm = lodash.cloneDeep(this.formInfo);
      // 处理数据
      deepForm.goods_cat = deepForm.goods_cat.join(",");
      // 3.处理商品参数
      let temp_arr = [];
      this.many_list.forEach((item) => {
        if (item.attr_vals.length) {
          temp_arr.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          });
        }
      });
      // 处理商品的属性;
      this.only_list.forEach((item) => {
        if (item.attr_vals.length) {
          temp_arr.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        }
      });
      // 把处理好的数据放到attts字段中
      deepForm.attr = temp_arr;
      // 发送请求
      let { data: res } = await this.$axios.post("goods", deepForm);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.$router.push("/goods");
    },
  },
};
</script>

<style lang="less" scoped>
.table-box {
  margin: 20px;
}
.stpes {
  margin-bottom: 20px;
}
/deep/ .ql-editor {
  min-height: 300px;
}
</style>